package com.jiamingZhao.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author ：JiaMing Zhao
 * @since ：2025/6/5 17:21
 */
public class ProxyFactory {


    public static <T> T getProxy(Object target) {
        Class<?> targetClass = target.getClass();
        @SuppressWarnings("unchecked")
        T t = (T) Proxy.newProxyInstance(
                targetClass.getClassLoader(),
                targetClass.getInterfaces(), // 获取目标所有接口
                (proxy, method, args) -> {
                    System.out.println("发现食物...");
                    Object result = method.invoke(target, args);
                    System.out.println("优雅的离开...");
                    return result;
                }
        );
        return t;
    }

    public static void main(String[] args) {
        Dog dog = new Dog();
//        Animal enhanceAnimal = ProxyFactory.getProxy(dog);
        Family enhanceFamily = ProxyFactory.getProxy(dog);
//        String eat = enhanceAnimal.eat();
//        String run = enhanceFamily.run();
//        System.out.println(run);
//        System.err.println(eat);
        World enhanceWorld =ProxyFactory.getProxy(dog);
        String eat = enhanceWorld.eat();
        String run = enhanceWorld.run();
        System.out.println(run);
        System.out.println(eat);
    }
}
